package com.example.logisticsingle.authorization;


import com.example.logisticsingle.Service.LoginService;
import com.example.logisticsingle.Service.UserService;
import com.example.logisticsingle.String.StringUtils;
import com.example.logisticsingle.constants.Config;
import com.example.logisticsingle.constants.ResponseEnum;
import com.example.logisticsingle.dto.Result;
import com.example.logisticsingle.dto.TokenInfo;
import com.example.logisticsingle.entity.SSOUser;
import com.example.logisticsingle.model.LoginLog;
import com.example.logisticsingle.model.UserInfo;
import com.example.logisticsingle.requsest.ClinetRequestInfo;
import com.example.logisticsingle.requsest.IPDetail;
import com.example.logisticsingle.requsest.RequestUtils;
import com.example.logisticsingle.utils.*;
import eu.bitwalker.useragentutils.DeviceType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;


/**
 *  登录成功操作
 *
 */
@Component
@Slf4j
public class SuccessAuthenticationHandler implements AuthenticationSuccessHandler {
    @Autowired
    private UserService userService;
    @Autowired
    private LoginService loginService;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        SSOUserDetail user = (SSOUserDetail) authentication.getPrincipal();
        String token = String.format("%s%s", AuthProperties.token.prefix, SSOTokenLoginHelper.generatorToken());
        log.info(user.getUsername()+"登录成功");
        Map<String, Object> params = RequestUtils.getParamsFormRequest(request);
        /*认证信息写入header*/
        String expireTime = (String) params.get(Config.TOKEN_EXPIRE_TIME);
        long expirTime = StringUtils.isNotNull(expireTime)?
                Long.parseLong(expireTime):AuthProperties.token.expireTime;
        SSOUser ssouser = user.getSsoUser();
        UserInfo userInfo = new UserInfo(ssouser.getUserid());
        String ip = request.getHeader(Config.REQUEST_IP);
        ip = StringUtils.isNull(ip)?RequestUtils.getIPAddress(request):ip;
        userInfo.setLoginIp(ip);
        userInfo.setLoginDate(new Date());
        log.info("update user :{}",userInfo);
        userService.updateUser(userInfo);
        SSOLoginStoreHelper.put(token, ssouser, expirTime);
        //记录日志
        LoginLog loginLog = new LoginLog();
        loginLog.setUserName(ssouser.getUsername());
        loginLog.setIpaddr(ip);
        loginLog.setLoginTime(new Date());
        loginLog.setMsg("登录成功");
        loginLog.setStatus("0");

        String str = request.getHeader(Config.REQUEST_TYPE);
        String request_type = StringUtils.isNull(str)?request.getParameter(Config.REQUEST_TYPE):str;
        if(StringUtils.isNotNull(request_type) && Integer.valueOf(request_type)==Config.REQUEST_TYPE_WEB) {
            ClinetRequestInfo clinetRequestInfo = RequestUtils.getClinetRequestInfo(request);
            if(null!=clinetRequestInfo) {
                loginLog.setBrowser(String.format("%s %s", clinetRequestInfo.getBrowserInfo().getName(),clinetRequestInfo.getBrowserVersion()));
                loginLog.setIpaddr(clinetRequestInfo.getIpInfo().getIp());
                loginLog.setLoginLocation(clinetRequestInfo.getIpInfo().getDesc());
                loginLog.setOs(clinetRequestInfo.getOsInfo().getName());
            }
            log.info("insert login log:{}",loginLog);
            loginService.insertLoginLog(loginLog);
            String rememberParm = (String) params.get(Config.REMEMBERME_NAME);
            boolean isRemember = StringUtils.isNotNull(rememberParm)?Boolean.getBoolean(rememberParm):false;
            try {
                CookieUtil.set(response, Config.SSO_SESSIONID, token, isRemember);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            String redit_url = (String) params.get(Config.REDIRECT_URL);
            if(StringUtils.isNull(redit_url)){
                RequestCache cache = new HttpSessionRequestCache();
                SavedRequest savedRequest = cache.getRequest(request, response);
                redit_url =  savedRequest==null? request.getContextPath()+"/":savedRequest.getRedirectUrl();
            }
            response.setHeader(AuthProperties.token.header,token);
            String split = redit_url.indexOf('?')!=-1?"&":"?";
            response.sendRedirect(redit_url+split+"access_token="+token);
        }else {
            String agent = request.getHeader(Config.REQUEST_USER_AGENT);
            agent = StringUtils.isNull(agent)?request.getHeader("User-Agent"):agent;
            ClinetRequestInfo clinetRequestInfo = RequestUtils.getClinetRequestInfo(agent,ip);
            if(null!=clinetRequestInfo) {
                loginLog.setBrowser(String.format("%s %s", clinetRequestInfo.getBrowserInfo().getName(),clinetRequestInfo.getBrowserVersion()));
                loginLog.setLoginLocation(clinetRequestInfo.getIpInfo().getDesc());
                loginLog.setOs(clinetRequestInfo.getOsInfo().getName());
                if(clinetRequestInfo.getDeviceType().equals(DeviceType.MOBILE.getName())) {
                    loginLog.setPhoneBrand(clinetRequestInfo.getMobileBrand());
                    loginLog.setPhoneModel(clinetRequestInfo.getMobileModel());
                    loginLog.setPhoneOs(clinetRequestInfo.getOsInfo().getName());
                }
            }else {
                IPDetail ipDetail = RequestUtils.getIpDetailInfo(ip);
                if(null != ipDetail)
                    loginLog.setLoginLocation(ipDetail.getDesc());
            }
            log.info("insert login log:{}",loginLog);
            loginService.insertLoginLog(loginLog);
            response.setHeader(AuthProperties.token.header,token);
            response.setStatus(HttpStatus.OK.value());
            response.setContentType("application/json;charset=UTF-8");
            Result<TokenInfo> result = ResultUtils.sucess(ResponseEnum.LOGIN_SUCCESS);
            TokenInfo tokeninfo = new TokenInfo();
            tokeninfo.setAccessToken(token);
            tokeninfo.setUser(ssouser);
            result.setData(tokeninfo);
            response.getWriter().write(JsonUtils.toJson(result));
        }
    }
}
